package generic

import (
	"fmt"
	"os"
	"strings"
	"webDownloader/engine/base"
	"webDownloader/utils"
)

func getUrl() (string, error) {
	// 从传入的参数中直接找出url
	for _, arg := range os.Args {
		if strings.HasPrefix(arg, "http") {
			return arg, nil
		}
	}
	html, err := utils.ReadUrlFromCfHtml()
	return html, err
}

var engines = make([]base.Engine, 0)

func RegisterEngine(engine base.Engine) {
	//fmt.Println("注册下载引擎: ", engine)
	engines = append(engines, engine)
}

func GetEngine() base.Engine {
	url, err := getUrl()
	if err != nil {
		fmt.Println("无法从输入中匹配下载引擎，请重新输入命令再试!")
		fmt.Println("提示信息: ", err)
		os.Exit(-1)
	}
	baseConf := map[string]interface{}{"refUrl": url, "hideDonate": false}
	for _, engine := range engines {
		if engine.Accept(url) {
			engine.SetConfig(baseConf)
			return engine
		}
	}
	return &EngineGeneric{
		Conf: baseConf,
	}

}
